var abuses = require('../models/abuse'),
    ideas = require('../models/idea'),
    apiHandler = require('../services/api-handler'),
    mailer = require('../mailer/mailer'),
    activity = require('../models/activity');

exports.reportAbuse = function (req, res) {
    var reportingUser = req.decoded._doc._id,
        reportedReason = req.body.reason,
        USER = req.user,
        reportedCategory = req.body.category;
    ideas.getIdeaById(req.body.ideaId, apiHandler.handler.check(res, 'NO_IDEA_FOUND', function (idea) {
        if (!idea || idea.length == 0) {
            var data = {
                ideaList: [],
                ideaCount: 0
            };
            apiHandler.setSuccessResponse(data,res);
        } else {
            var abuseData = {
                "user": USER._id,
                "reason": reportedReason
            };
            idea.abuse.push(abuseData);
            idea.save();
            var reportAbuse = new abuses({
                "user": reportingUser,
                "category": reportedCategory,
                "reason": reportedReason,
                "idea": idea
            });
            abuses.createNewAbuse(reportAbuse, apiHandler.handler.check(res, 'IDEA_ABUSE_FAILED', function (abuse) {

                ideas.updateAbuseCount(idea._id);
                var iLink = '/v1/ideas/getIdeaById';
                mailer.sendAbuseReportedMail(USER.firstName, USER.lastName, reportedReason, idea, iLink)
                    .then(function (success) {
                    })
                    .catch(function (err) {
                        apiHandler.setErrorResponse('ERROR_WHILE_MAIL_SENDING', res);
                    });
                var newActivity = new activity({
                    activityType: "Reported abuse",
                    idea: idea,
                    user: reportingUser,
                    abuse: abuse
                });
                activity.createNewActivity(newActivity, apiHandler.handler.check(res, 'ACTIVITY_FAILED', function (activity) {
                    apiHandler.setSuccessResponse(abuse, res);
                }));
            }));
        }
    }));
};

exports.getAllAbuses = function (req, res) {
    var data;
    abuses.getAllAbuses(req.user._id, req.body, apiHandler.handler.check(res, 'NO_ABUSE', function (abuses) {
        if (!abuses || abuses.length == 0) {
            data ={
                abuseList: [],
                abuseCount: 0
            };
            apiHandler.setSuccessResponse(data,res);
        } else {
            data = {
                abuseList: abuses,
                abuseCount: abuses.length
            };
            apiHandler.setSuccessResponse(data,res);
        }
    }));
};

